/*   Ajax start   */
/*	封装Ajax
	ajax({
		type: 'get',
		url: '',
		async: 'true',
		data: {
			name: 'QYGK',
			age: 18
		}
		contentType: 'application/json',
		beforeSend: function(){}
		success: function(){}
		error: function(){}

	});
*/
function ajax(options) {
	let ajaxData = {
		type: (options.type || 'GET').toUpperCase(),
		url: options.url || '',
		async: true,
		data: options.data || null, 
		contentType: options.contentType || 'application/x-www-form-urlencoded',
		beforeSend: options.beforeSend || function(){},
		success: options.success || function(){},
		error: options.error || function(){}
	}
	// 此处在ajaxData里不能使用async: options.async || true,因为如果值为false，不会返回false而是返回后面的true，这样的话同步就不起效果了。 
	if(options.async == false) {
		ajaxData.async = false;
	}
	// 获取Ajax对象
	let xhr = new createXMLHttpRequest();
	// 获取参数
	let params = convertParams(ajaxData.data, ajaxData.contentType);
	xhr.onload = function() {
		if(xhr.status == 200) {
			ajaxData.success(xhr);	
		} else {
			ajaxData.error(xhr);
		}
	}

	ajaxData.beforeSend();
	if(ajaxData.type == 'POST') {
		xhr.open(ajaxData.type, ajaxData.url, ajaxData.async);
		xhr.setRequestHeader('Content-Type', ajaxData.contentType);
		xhr.send(params);
	} else {
		if(params) {
			xhr.open(ajaxData.type, ajaxData.url + '?' + params, ajaxData.async);
		} else {
			xhr.open(ajaxData.type, ajaxData.url, ajaxData.async);
		}
		xhr.send(null);
	}
}

/*
	功能：对数据进行转换
	参数1：data
	参数2：contentType
	返回值：参数字符串
*/
function convertParams(data, contentType) {
	if(contentType == 'application/json') {
		// 响应参数为json格式的字符串
		return JSON.stringify(data);
	}
	/*if(data instanceof FormData) {
		return data;
	}
	if(typeof data == 'string') {
		return data;
	}*/
	if(typeof data == 'object') {
		// 若data为一个对象
		let arr = [];
		for(let key in data) {
			arr.push(key + '=' + data[key]);
		}
		return arr.join('&');
	} else {
		return data;
	}
}

/*
	功能：创建Ajax对象
	返回值：Ajax对象，或抛异常
*/
function createXMLHttpRequest() {
	try {
		return new XMLHttpRequest();
	} catch (e) {
		try {
			return new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				return new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("您使用的浏览器版本过低，请更新浏览器！");
				throw e;
			}
		}
	}
}
/*   Ajax end   */

/*   others start    */
/*
	移除所有子元素（不包括自己）
*/

function removeAllChildren(parentEle) {
	while(parentEle.children.length > 0) {
		parentEle.removeChild(parentEle.children[0]);
	}
}

/*
	功能：移除所有子元素（包括自己）
	参数：元素
*/
function removeWorld(root) {
	let children = root.children;
	for(let i = 0; i< children.length; i++) {
		let ele = children[i];
		if(ele.children.length > 0) {
			removeWorld(ele);
		} else {
			ele.remove();
		}
	}
	root.remove();
}

/*
	功能：添加toast
*/
function toast(content, backgroundColor, time) {
	let div = document.createElement('div');
	div.className = 'toast';
	div.innerText = content;
	document.body.appendChild(div);
	let delayTime = time || 2000;
	if(backgroundColor) {
		div.style.backgroundColor = backgroundColor;
	}
	setTimeout(() => {
		div.style.opacity = 1;
	}, 10);
	setTimeout(() => {
		document.body.removeChild(div);
	}, delayTime);
}

/*
	功能：去除父元素下所有子元素className里面的指定类名
	参数1：父元素
	参数2：指定要移除的类名，该类名必须处于className最后的位置上
*/
function removeStyle(parentEle, styleName) {
	let items = parentEle.children;
	for(let i = 0; i < items.length; i++) {
		let item = items[i];
		let className = item.className;
		let index = 0;
		if(className == styleName) {
			className = '';
		} else if((index = className.indexOf(' ' + styleName)) != -1) {
			className = className.substring(0, index);
		}
		item.className = className;
	}
}

/*
 * 	功能：查询购物车项的数量
 * 	返回值：查询到的数量
 * */
function cartCount() {
	let count = null;
	ajax({
		type: 'POST',
		async: false,
		url: '/cart/myCart',
		success: function(xhr) {
			let arg = JSON.parse(xhr.responseText);
			if(arg.code == 200) {
				let dataArray = arg.data;
				if(dataArray) {
					count = dataArray.length;
				} else {
					count = 0;
				}
			}
		}
	});
	return count;
}

/*
 *	功能：从cookie中根据key值去value
 *	参数1：key 
 * 
 * */
function getCookieValue(key) {
	let cookie = document.cookie;
	if(cookie.length > 0) {
		let startIndex = cookie.indexOf(key);
		if(startIndex != -1) {
			// 存在key
			let endIndex = cookie.indexOf(';', startIndex + key.length + 1)
			if(endIndex == -1) {
				// 说明是最后一个
				endIndex = cookie.length;
			}
			let value = cookie.substring(startIndex + key.length + 1, endIndex);
			return unescape(value.trim());
		}
	}
	// 若没有cookie或找不到key则返回null
	return null;
}
/*   others end   */